package com.cc.study.lifecycle;

import com.cc.study.di.BookDao;
import com.cc.study.di.BookService;
import com.cc.study.ioc.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.lang.reflect.InvocationTargetException;

public class TestLifecycle {

    @Test
    public void demo01() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String xmlPath = "lifecycle.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        UserService userService = (UserService) applicationContext.getBean("userServiceId");
        userService.addUser();
        //要求：1.容器必须close，销毁方法执行; 2.必须是单例的
//		applicationContext.getClass().getMethod("close").invoke(applicationContext);
        // * 此方法接口中没有定义，实现类提供
//        applicationContext.close();
        applicationContext.getClass().getMethod("close").invoke(applicationContext);
    }

    @Test
    public void demo02(){
        String xmlPath = "lifecycle.xml";
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        UserService userService = (UserService) applicationContext.getBean("userServiceId");
        userService.addUser();
        applicationContext.registerShutdownHook();
    }

    @Test
    public void demo03(){
        String xmlPath = "default-lifecycle.xml";
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        UserService userService = (UserService) applicationContext.getBean("userServiceId");
        userService.addUser();
        applicationContext.registerShutdownHook();
    }

    @Test
    public void demo04(){
        String xmlPath = "lifecycle2.xml";
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        InitHelloWorld initHelloWorld = applicationContext.getBean("initHelloWorld",InitHelloWorld.class);
        initHelloWorld.getMessage();
        applicationContext.registerShutdownHook();
    }

    @Test
    public void demo05(){
        String xmlPath = "lifecycle3.xml";
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        BookDao bookDao = applicationContext.getBean("bookDaoId",BookDao.class);
        bookDao.addBook();
    }
}
